'use client'

import { useState } from 'react'
import { Card, Button, Input, Typography, Space, Select, Tabs, message } from 'antd'
import { CopyOutlined, SwapOutlined, ClearOutlined } from '@ant-design/icons'

const { TextArea } = Input
const { Title, Text } = Typography
const { Option } = Select

const CONVERSION_TYPES = [
  { value: 'json', label: 'JSON格式化' },
  { value: 'xml', label: 'XML格式化' },
  { value: 'base64', label: 'Base64编码/解码' },
  { value: 'url', label: 'URL编码/解码' },
  { value: 'case', label: '大小写转换' },
  { value: 'timestamp', label: '时间戳转换' },
]

export default function FormatConverter() {
  const [input, setInput] = useState('')
  const [output, setOutput] = useState('')
  const [conversionType, setConversionType] = useState('json')

  const convert = () => {
    try {
      let result = ''
      
      switch (conversionType) {
        case 'json':
          result = JSON.stringify(JSON.parse(input), null, 2)
          break
        case 'xml':
          result = formatXML(input)
          break
        case 'base64':
          if (isBase64(input)) {
            result = atob(input)
          } else {
            result = btoa(input)
          }
          break
        case 'url':
          if (isURLEncoded(input)) {
            result = decodeURIComponent(input)
          } else {
            result = encodeURIComponent(input)
          }
          break
        case 'case':
          result = input.toUpperCase()
          break
        case 'timestamp':
          result = convertTimestamp(input)
          break
        default:
          result = input
      }
      
      setOutput(result)
      message.success('转换成功')
    } catch (error) {
      message.error('转换失败：' + (error as Error).message)
    }
  }

  const swap = () => {
    setInput(output)
    setOutput(input)
  }

  const clear = () => {
    setInput('')
    setOutput('')
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
    message.success('已复制到剪贴板')
  }

  const isBase64 = (str: string) => {
    try {
      return btoa(atob(str)) === str
    } catch {
      return false
    }
  }

  const isURLEncoded = (str: string) => {
    return str.includes('%')
  }

  const formatXML = (xml: string) => {
    // 简单的XML格式化
    return xml.replace(/></g, '>\n<')
  }

  const convertTimestamp = (input: string) => {
    const timestamp = parseInt(input)
    if (isNaN(timestamp)) {
      throw new Error('无效的时间戳')
    }
    return new Date(timestamp * 1000).toLocaleString()
  }

  return (
    <div>
      <Title level={2}>格式转换</Title>
      <Text type="secondary">各种格式转换工具</Text>
      
      <Card style={{ marginTop: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <Text>转换类型：</Text>
            <Select 
              value={conversionType} 
              onChange={setConversionType}
              style={{ width: 200 }}
            >
              {CONVERSION_TYPES.map(type => (
                <Option key={type.value} value={type.value}>
                  {type.label}
                </Option>
              ))}
            </Select>
          </div>

          <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
            {/* 输入区域 */}
            <div style={{ flex: 1 }}>
              <Text strong>输入：</Text>
              <TextArea
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="请输入要转换的内容..."
                autoSize={{ minRows: 10, maxRows: 15 }}
                style={{ marginTop: 8 }}
              />
            </div>

            {/* 操作按钮 */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 32 }}>
              <Button 
                type="primary" 
                onClick={convert}
                disabled={!input.trim()}
              >
                转换
              </Button>
              <Button 
                icon={<SwapOutlined />}
                onClick={swap}
                disabled={!input.trim() || !output.trim()}
              >
                交换
              </Button>
              <Button 
                icon={<ClearOutlined />}
                onClick={clear}
              >
                清空
              </Button>
            </div>

            {/* 输出区域 */}
            <div style={{ flex: 1 }}>
              <Text strong>输出：</Text>
              <div style={{ position: 'relative', marginTop: 8 }}>
                <TextArea
                  value={output}
                  readOnly
                  autoSize={{ minRows: 10, maxRows: 15 }}
                  style={{ backgroundColor: '#fafafa' }}
                />
                {output && (
                  <Button
                    size="small"
                    icon={<CopyOutlined />}
                    onClick={() => copyToClipboard(output)}
                    style={{ position: 'absolute', top: 8, right: 8 }}
                  >
                    复制
                  </Button>
                )}
              </div>
            </div>
          </div>
        </Space>
      </Card>
    </div>
  )
} 